package com.appserver.web.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 参数信息切面
 * Created by guoyanjiang on 2018/5/5.
 */
@Aspect
@Component
public class ParamInfoLogAspect {

    Logger logger = LoggerFactory.getLogger(getClass());

    @AfterThrowing("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controller(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        RequestMapping requestMapping = signature.getMethod().getAnnotation(RequestMapping.class);
        String path = requestMapping.path() != null ? requestMapping.path()[0] : requestMapping.value()[0];
        RequestMethod method = requestMapping.method()[0];
        logger.error("[{} {}] error-request-params: {}", method.name(), path, getMethodParams(point));
    }

    @AfterThrowing("bean(httpResourceImpl)")
    public void httpResource(JoinPoint point) {
        logger.error("forward-error-request-params: {}", getMethodParams(point));
    }


    private String getMethodParams(JoinPoint point) {
        String[] parameterNames = ((MethodSignature) point.getSignature()).getParameterNames();
        StringBuilder sb = null;
        if (parameterNames != null) {
            sb = new StringBuilder();
            for (int i = 0; i < parameterNames.length; i++) {
                String value = point.getArgs()[i] != null ? point.getArgs()[i].toString() : "";
                sb.append(parameterNames[i] + ":" + value + " ");
            }
            return sb.toString();
        }
        return "";
    }
}
